package com.eight.cloud.job.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.eight.cloud.job.entity.QuartzJobEntity;
import com.eight.cloud.job.mapper.QuartzJobMapper;
import com.eight.cloud.job.model.dto.QuartzJobDto;
import com.eight.cloud.job.service.IQuartzJobService;
import com.eight.cloud.mybatisplus.service.BaseService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

import static com.eight.cloud.core.global.constant.NumConstant.ONE;

/**
 * @ClassName: QuartzJobServiceImpl
 * @Author: TXC
 * @Date: 2025-02-25 10:11
 **/
@Service
public class QuartzJobServiceImpl extends BaseService<QuartzJobMapper, QuartzJobEntity> implements IQuartzJobService {
    @Override
    public void getPage(IPage<QuartzJobEntity> page) {
        baseMapper.selectPage(page, null);
    }

    @Override
    public QuartzJobEntity createQuartzJob(QuartzJobDto quartzJob) {
        if (ObjectUtil.isNotNull(quartzJob) && ObjectUtil.isNull(getQuartzJobByInvokeTarget(quartzJob.getInvokeTarget()))) {
            QuartzJobEntity quartzJobEntity = convertToEntity(quartzJob);
            quartzJobEntity.setStatus(ONE);
            baseMapper.insert(quartzJobEntity);
            return quartzJobEntity;
        }
        return null;
    }

    @Override
    public boolean updateQuartzJob(QuartzJobDto quartzJob) {
        if (quartzJob != null) {
            QuartzJobEntity quartzJobEntity = convertToEntity(quartzJob);
            updateByUuid(quartzJobEntity);
            return true;
        }
        return false;
    }

    @Override
    public boolean deleteQuartzJob(String uuid) {
        return removeByUuid(uuid);
    }

    @Override
    public QuartzJobEntity getQuartzJobByInvokeTarget(String invokeTarget) {
        return baseMapper.selectOne(new LambdaQueryWrapper<QuartzJobEntity>()
                .eq(QuartzJobEntity::getInvokeTarget, invokeTarget));
    }

    @Override
    public List<String> deleteQuartzJobIgnore(List<String> invokeTargets) {
        List<QuartzJobEntity> quartzJobEntities = baseMapper.selectList(lambdaQueryWrapper()
              .notIn(QuartzJobEntity::getInvokeTarget, invokeTargets));
        List<String> uuids = quartzJobEntities.stream().map(QuartzJobEntity::getUuid).collect(Collectors.toList());
        if (!uuids.isEmpty()) {
            baseMapper.realDelete(new LambdaQueryWrapper<QuartzJobEntity>().in(QuartzJobEntity::getUuid, uuids));
        }
        return uuids;
    }
}
